package com.angel.controller;

import com.angel.bean.*;
import com.angel.bean.dto.BabyInfoDto;
import com.angel.dto.VipUserBabyDto;
import com.angel.dtoutlis.VipUserBabyDtoUtil;
import com.angel.service.*;
import com.angel.dto.getOrderIdByUUId;
import com.angel.shiro.SystemAdminAuthorizingRealm;
import com.angel.utils.AdminUserUtils;
import com.angel.utils.LogUtils;
import net.sf.json.JSONArray;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/process")
public class ProcessingController {
    @Autowired
    private VipInfoService vipInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BabyInfoService babyInfoService;

    @Autowired
    private VipCardService vipCardService;

    @Autowired
    private SysmptomTypeService sysmptomTypeService;

    @Autowired
    private IllCaseService illCaseService;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private ProductService productService;

    @Autowired
    private AcupuncturePointService acupuncturePointService;

    @Autowired
    private NoticeMaterService noticeMaterService;

    @Autowired
    private PrescriptionService prescriptionService;

    @Autowired
    private EmployeeTypeService employeeTypeService;

    @Autowired
    private OtherlogService otherlogService;

    @Autowired
    private BranchesService branchesService;

    /**
     * 进入流程处理第一步
     *
     * @return
     */
    @RequestMapping("/first")
    public String firtsProcess() {
        return "firstprocess";
    }

    @RequestMapping("/second")
    public String secondProcess(@RequestParam(value = "id") String id, Model model) {
        Integer illId = null;
        try {
            illId = Integer.valueOf(id);
        } catch (Exception e) {

        }
        IllCase illCase = new IllCase();
        illCase.setIllCaseId(illId);
        if (illId != null) {
            illCase = illCaseService.findOne(illCase);

            if (illCase != null) {
                model.addAttribute("illcase", illCase);
                UserInfo userInfo = new UserInfo();
                userInfo.setId(illCase.getUserId());
                userInfo = userInfoService.findOne(userInfo);
                if (userInfo != null) {
                    model.addAttribute("userInfo", userInfo);
                }
                BabyInfo babyInfo = new BabyInfo();
                babyInfo.setBabyId(illCase.getBabyId());
                babyInfo = babyInfoService.findOne(babyInfo);
                if (babyInfo != null) {
                    model.addAttribute("babyInfo", babyInfo);
                }
            } else {
                return "redirect:/illCaseController/getillcase?status=0";
            }
        }
        return "sysmpType";
    }

    @PostMapping("/search")
    @ResponseBody
    public Object SearchInfo(@Param("type") String type, @Param("content") String content) {
        //去除空格
        content = content.trim().replaceAll(" ", "");
        VipInfo vipInfo = null;
        UserInfo userInfo = null;
        BabyInfo babyInfo = null;
        List<VipInfo> vipInfos = null;
        List<UserInfo> userInfos = null;
        List<BabyInfoDto> babyInfos = null;
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        switch (type) {
            case "vipno":
                //会员卡号
                vipInfo = new VipInfo();
                vipInfo.setVipNo(content);
                vipInfos = vipInfoService.searchVipInfo(vipInfo);
                break;
            case "phone":
                //父母电话号码
                userInfo = new UserInfo();
                userInfo.setUserTel(content);
                userInfos = userInfoService.searchUserInfo(userInfo);
                break;
            case "pname":
                //父母名字
                userInfo = new UserInfo();
                userInfo.setUserName(content);
                userInfos = userInfoService.searchUserInfo(userInfo);
                break;
            case "bname":
                //宝宝名字
                babyInfo = new BabyInfo();
                babyInfo.setBabyName(content);
                babyInfos = babyInfoService.searchBabyInfo(babyInfo);
                break;
            case "fileno":
                //纸质档案编号
                babyInfo = new BabyInfo();
                babyInfo.setFileNo(content);
                babyInfos = babyInfoService.searchBabyInfo(babyInfo);
                break;
            default:
                break;

        }
        List<VipUserBabyDto> userBabyDtos = VipUserBabyDtoUtil.getVipUserBabyInfos(babyInfos, babyInfoService, userInfos, userInfoService, vipInfos, vipInfoService, vipCardService, et);
        if (userBabyDtos != null && userBabyDtos.size() > 4) {
            for (int i = 5; i < userBabyDtos.size(); i++) {
                userBabyDtos.remove(i);
            }
        }
        return userBabyDtos;
    }

    /**
     * 获取单个用户信息
     *
     * @return
     */
    @PostMapping("/one")
    @ResponseBody
    public Object getInfo(@Param("uid") String uid) {
        int id = 0;
        try {
            id = Integer.valueOf(uid);
        } catch (Exception e) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        List<UserInfo> userInfos = userInfoService.findAll(userInfo);
        if (userInfos == null || userInfos.isEmpty()) {
            return null;
        }
        Employee et = AdminUserUtils.getPrincipal().getEmployee();
        List<VipUserBabyDto> userBabyDtos = VipUserBabyDtoUtil.getVipUserBabyInfos(null, babyInfoService, userInfos, userInfoService, null, vipInfoService, vipCardService, et);
        if (userBabyDtos != null && !userBabyDtos.isEmpty()) {
            return userBabyDtos.get(0);
        }
        return null;
    }

    /**
     * 获取症状类型
     *
     * @return
     **/
    @PostMapping("/AllSysmptomType")
    @ResponseBody
    public Object findAllSysmptomType() {
        SysmptomType sysmptomType = new SysmptomType();
        sysmptomType.setState(1);
        List<SysmptomType> SysmptomTypes = sysmptomTypeService.findAll(sysmptomType);
        if (SysmptomTypes == null || SysmptomTypes.isEmpty()) {
            return null;
        }
        return SysmptomTypes;
    }

    /**
     * 开放处理第三步
     *
     * @return
     */
    @RequestMapping("/third")
    public String getThirdProcess(Model model, @Param("id") String id) {
        Integer illCaseId = null;
        try {
            illCaseId = Integer.valueOf(id);
            model.addAttribute("id", illCaseId);
        } catch (Exception e) {
            return "index";
        }
        IllCase tmp = new IllCase();
        tmp.setIllCaseId(illCaseId);
        IllCase illCase = illCaseService.findOne(tmp);
        if (illCase != null) {
            model.addAttribute("illCase", illCase);
        } else {
            return "redirect:/illCaseController/getillcase?status=1";
        }
        return "thirdprocess";
    }

    @RequestMapping("/getillcasedetail")
    @ResponseBody
    public Object getIllCase(IllCase illCase) {
        illCase = illCaseService.findOne(illCase);
        if (illCase == null) {
            return null;
        } else {
            System.out.println(illCase.getSysmptom());
            return illCase;
        }
    }

    @RequestMapping("/getTemplate")
    @ResponseBody
    public Object getTemplate(Template template) {
        template.setState(1);
        List<Template> mList = templateService.findTemplate(template);
        if (mList.size() > 0) {
            System.out.println(mList);
            return mList;
        } else {
            return null;
        }
    }

    @RequestMapping("/getProduct")
    @ResponseBody
    public Object getProduct(Product product) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        Product pro = productService.findOne(product);
        if (pro != null) {
            map.put("pro", pro);
        }
        return map;
    }

    @RequestMapping("/searchProduct")
    @ResponseBody
    public Object searchProduct(Product product) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        SystemAdminAuthorizingRealm.Principal employee = AdminUserUtils.getPrincipal();
        product.setBranId(employee.getEmployee().getBranchesId());
        List<Product> mList = productService.searchProduct(product);
        if (mList.size() > 0) {
            map.put("productList", mList);
        }
        return map;
    }

    @RequestMapping("/searchAcupByOneTarget")
    @ResponseBody
    public Object searchAcupByOneTarget(AcupuncturePoint acupuncturePoint) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        acupuncturePoint.setState(1);
        List<AcupuncturePoint> mList = acupuncturePointService.searchAcupByOneTarget(acupuncturePoint);
        if (mList.size() > 0) {
            map.put("acupList", mList);
        }
        return map;
    }

    @RequestMapping("/findAllNotice")
    @ResponseBody
    public Object findAllNotice(NoticeMater noticeMater) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        List<NoticeMater> mList = noticeMaterService.findNoticeMater(noticeMater);
        if (mList.size() > 0) {
            map.put("noticeList", mList);
        }
        return map;
    }

    @RequestMapping("/getFinallyPres")
    public Object getFinallyPres() {

        return "finalprocess";
    }

    @RequestMapping("/addPrescription")
    @ResponseBody
    public Object addPrescription(Prescription prescription) {
        Map<Object, Object> map = new HashMap<Object, Object>();

        //查询当前开单员工的姓名;
        Employee employee = AdminUserUtils.getPrincipal().getEmployee();

        Prescription tempPresc = new Prescription();
        //查询是否存在同一张病历的处方
        tempPresc.setIllCaseId(prescription.getIllCaseId());
        Prescription result_pres = prescriptionService.findon(tempPresc);
        //如果存在执行开单以及更新病历状态
        if (result_pres != null) {
            map.put("fail", "一张病历只能开一张单");
        } else {
            prescription.setPresNo(getOrderIdByUUId.getOrderIdByUUId());
            prescription.setCreatPresDate(new Timestamp(System.currentTimeMillis()));
            prescription.setTemId(employee.getEmName());
            try {
                Map temp = prescriptionService.deailPres(prescription);
                map.put("data", temp);
                map.put("success", true);
            } catch (Exception e) {
                map.put("error", "处理失败");
            }
        }


        return map;
    }

    @RequestMapping("/getAllIllCase")
    @ResponseBody
    public Object getAllIllCase(IllCase illCase) {
        illCase.setState(1);

        List<IllCase> illCaseList = illCaseService.findIllCase(illCase);

        if (illCaseList != null) {
            return illCaseList;
        }
        return null;
    }

    @RequestMapping("/regetIllCase")
    public Object regetIllCase(@RequestParam(value = "id") String id, Model model) {
        Integer illId = null;
        try {
            illId = Integer.valueOf(id);
        } catch (Exception e) {

        }

        IllCase illCase = new IllCase();
        illCase.setIllCaseId(illId);
        illCase.setSysmptom("");
        illCase.setOtherSysmp("");
        illCase.setIllCaseState(0);
        int result = illCaseService.update(illCase);
        if (result > 0) {
            return "redirect:/illCaseController/getillcase?status=0";
        }
        return "404";
    }


    /**
     * 获取预约，进入流程处理第一步
     *
     * @return
     */
    @RequestMapping("prefirst")
    public String getPreInfo(@RequestParam(value = "id") String id, Model model) {
        Integer illId = null;
        try {
            illId = Integer.valueOf(id);
        } catch (Exception e) {

        }
        IllCase illCase = new IllCase();
        illCase.setIllCaseId(illId);
        if (illId != null) {
            illCase = illCaseService.findOne(illCase);
            if (illCase != null) {
                model.addAttribute("illcase", illCase);
            } else {
                return "index";
            }
        }
        return "prefirstprocess";
    }


    @RequestMapping("/settlment")
    @ResponseBody
    public Map settlementIllcase(@RequestParam(value = "illid") String illid) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        Integer illids = null;
        try {
            illids = Integer.valueOf(illid);
        } catch (Exception e) {

        }
        //判断当前员工是否有结算权限
        Employee employee = AdminUserUtils.getPrincipal().getEmployee();
        EmployeeType employeeType = new EmployeeType();
        employeeType.setEmTypeId(employee.getEmTypeId());
        employeeType = employeeTypeService.findOneType(employeeType);
        if (employeeType != null) {
            //店长、管理员、收银员有结算权限
            if ("admin".equals(employeeType.getTypeName()) || "shopAdmin".equals(employeeType.getTypeName()) || "cashier".equals(employeeType.getTypeName()) || employeeType.getTypeName().contains("admin") || employeeType.getTypeName().contains("Admin")) {
                Branches branches = new Branches();
                branches.setBranId(employee.getBranchesId());
                branches = branchesService.findOneBranches(branches);
                IllCase illCase = new IllCase();
                illCase.setIllCaseId(illids);
                illCase = illCaseService.findOne(illCase);
                //判断该条病例信息是否存在
                if (illCase != null && illCase.getIllCaseState() == 4) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setId(illCase.getUserId());
                    //查询出当前用户对应的用户信息
                    userInfo = userInfoService.findOne(userInfo);
                    VipInfo vipInfo = new VipInfo();
                    vipInfo.setUserId(userInfo.getId());
                    //查询出当前对应的会员卡信息
                    vipInfo = vipInfoService.findOne(vipInfo);

                    //先判断会员卡类型，如果是体验卡，则扣除体验卡次数
                    VipCard vipCard = new VipCard();
                    vipCard.setVipId(vipInfo.getVipId());
                    vipCard = vipCardService.findOne(vipCard);
                    if (vipCard.getVipLevel() == 0) {
                        if (vipInfo.getRemainTime() == 0) {
                            result.put("msg", "该会员卡是体验卡，体验次数不足，请充值或者升级会员卡等级！");
                            return result;
                        }
                    }


                    //判断当前会员卡是否在当前店铺消费
                    if (vipInfo.getBranId() == employee.getBranchesId()) {
                        //查询出当前处方详情
                        Prescription prescription = new Prescription();
                        prescription.setIllCaseId(illCase.getIllCaseId());
                        prescription = prescriptionService.findon(prescription);
                        if (prescription == null) {
                            result.put("msg", "处方信息不存在，不能结算！");
                            return result;
                        } else {
                            //结算处理
                            JSONArray jsonArray = JSONArray.fromObject("[" + prescription.getPresDetail() + "]");
                            List<Map> presDetailMap = new ArrayList<>();
                            for (int i = 0; i < jsonArray.size(); i++) {
                                Map<String, Object> map = (Map) jsonArray.get(i);
                                presDetailMap.add(map);
                            }

                            //将商品和穴位区分开map来；
                            //商品map
                            List<Map> dietaryMap = new ArrayList<>();
                            //穴位map
                            List<Map> nurseMap = new ArrayList<>();
                            for (int i = 0; i < presDetailMap.size(); i++) {
                                Map<String, Object> tmap = presDetailMap.get(i);
                                if ("nurse".equals(tmap.get("pretype").toString())) {
                                    //如果是穴位
                                    nurseMap.add(tmap);
                                } else if ("dietary".equals(tmap.get("pretype").toString())) {
                                    //如果是商品
                                    dietaryMap.add(tmap);
                                }
                            }
                            Product product = new Product();
                            product.setBranId(employee.getBranchesId());
                            //查询出当前分店的所有商品
                            List<Product> productList = productService.findProduct(product);


                            //比对商品是否满足，否则结算失败
                            //数量不够的商品noEnoughProduct里面
                            List<Map> noEnoughProduct = new ArrayList<>();
                            //该分店没有的商品
                            List<Map> noExistProduct = new ArrayList<>();
                            //处方所需要的所有商品记录
                            List<Product> needProducts = new ArrayList<>();
                            for (int i = 0; i < dietaryMap.size(); i++) {
                                Map<String, Object> pmap = dietaryMap.get(i);
                                boolean isExist = true;
                                for (int j = 0; j < productList.size(); j++) {
                                    Product tproduct = productList.get(j);
                                    if (pmap.get("prename").equals(tproduct.getReserve1())) {
                                        //存在的商品
                                        isExist = false;
                                        if (tproduct.getProStock() - 1 < Integer.valueOf(pmap.get("precount").toString())) {
                                            //库存不足
                                            noEnoughProduct.add(pmap);
                                        }
                                        tproduct.setState(Integer.valueOf(pmap.get("precount").toString()));
                                        needProducts.add(tproduct);
                                    }
                                }
                                if (isExist) {
                                    //不存在的商品
                                    noExistProduct.add(pmap);
                                }

                            }

                            Map tres = new HashMap();
                            if (noEnoughProduct.size() > 0) {
                                //商品数量不足
                                tres.put("msg", "商品库存不足");
                                tres.put("enough", noEnoughProduct);
                            }
                            if (noExistProduct.size() > 0) {
                                //商品数量不足
                                tres.put("msg1", "有商品不存在");
                                tres.put("noexist", noExistProduct);
                            }

                            //商品足够且满足全
                            if (noEnoughProduct.size() == 0 && noExistProduct.size() == 0) {
                                //判断是否有商品模板被更改
                                //所有的模板id
                                Set<Integer> tmpset = new HashSet<Integer>();
                                //1.取出所有的模板的商品,单个商品
                                //模板商品

                                Map<Integer, List> tmplateMap = new HashMap<>();
                                //单个商品，结算使用,status作为临时的购买量
                                List<Product> aloneProduct = new ArrayList<>();
                                for (int i = 0; i < dietaryMap.size(); i++) {
                                    Map map = dietaryMap.get(i);
                                    Integer tmpid = Integer.valueOf(map.get("pretemid").toString());
                                    if (tmpid == 0) {
                                        //单个商品
                                        for (int j = 0; j < needProducts.size(); j++) {
                                            if (needProducts.get(j).getReserve1().equals(map.get("prename"))) {
                                                Integer count = Integer.valueOf(map.get("precount").toString());
                                                needProducts.get(j).setState(count);
                                                if (!aloneProduct.contains(needProducts.get(j))){
                                                    aloneProduct.add(needProducts.get(j));
                                                }

                                            }
                                        }
                                    } else {
                                        // 所有模板商品
                                        tmpset.add(tmpid);
                                        if (tmplateMap.containsKey(tmpid)) {
                                            tmplateMap.get(tmpid).add(map);
                                        } else {
                                            List<Map> tmproduct = new ArrayList<>();
                                            tmproduct.add(map);
                                            tmplateMap.put(tmpid, tmproduct);
                                        }

                                    }
                                }
                                //遍历查出所有的模板集合
                                List<Template> nochangeTemp = new ArrayList<>();
                                //  List<Template> templateList = new ArrayList<>();
                                if (tmpset.size() > 0) {
                                    for (Integer tid : tmpset) {
                                        Template template = new Template();
                                        template.setTemId(tid);
                                        //数据库存储的模板数据
                                        template = templateService.findOne(template);
                                        //用户存储的模板数据
                                        List<Map> userProductList = tmplateMap.get(tid);
                                        if (template != null) {
                                            JSONArray tm = JSONArray.fromObject(template.getTemDetail());
                                            int count = 0;
                                            for (int i = 0; i < tm.size(); i++) {
                                                Map dbmap = (Map) tm.get(i);
                                                for (int j = 0; j < userProductList.size(); j++) {
                                                    Map usermap = userProductList.get(j);
                                                    Product tppp = new Product();
                                                    tppp.setProductId(Integer.valueOf(dbmap.get("Reid").toString()));
                                                    tppp = productService.findOne(tppp);
                                                    if (tppp.getReserve1().equals(usermap.get("prename")) && dbmap.get("productCount").equals("precount")) {
                                                        count++;
                                                    }
                                                }
                                            }
                                            if (count == tm.size()) {
                                                //没有改变模板
                                                nochangeTemp.add(template);
                                            } else {
                                                //模板已经改变
                                                for (int i = 0; i < tm.size(); i++) {
                                                    Map dbmap = (Map) tm.get(i);
                                                    Product tppp1 = new Product();
                                                    tppp1.setProductId(Integer.valueOf(dbmap.get("Reid").toString()));
                                                    tppp1 = productService.findOne(tppp1);
                                                    for (Product need : needProducts) {
                                                        if (need.getReserve1().equals(tppp1.getReserve1())) {
                                                            if (!aloneProduct.contains(need)){
                                                                aloneProduct.add(need);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                //  将nochangeTem和aloneProduct，nurseMap(穴位模板)传入即可做商品结算，剩下的是穴位结算
                                Map setlementMap = null;
                                try {
                                    setlementMap = productService.settlementPrice(illCase, vipInfo, employee, branches, nochangeTemp, aloneProduct, nurseMap);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                boolean payres = (boolean) setlementMap.get("success");
                                String msg = "";
                                if (payres) {
                                    msg = (String) setlementMap.get("pay");
                                    result.put("success", true);
                                } else {
                                    msg = (String) setlementMap.get("pay");
                                }

                                result.put("msg", msg);

                            } else {
                                result.put("data", tres);
                            }

                        }
                    } else {
                        result.put("msg", "会员卡和分店不符合");
                    }
                } else {
                    result.put("msg", "该信息不存在或该状态不能结算");
                }
            }
        } else {
            result.put("msg", "该员工没有结算权限");
        }
        String msg = "员工" + employee.getEmName() + "进行结算" + result.get("msg");

        LogUtils.InsertLog(employee, otherlogService, msg);
        return result;
    }

    @RequestMapping("/printPrescription")
    public String printPrescription(@RequestParam("ilid") String ilid, Model model) {
        Integer illid = null;
        try {
            illid = Integer.valueOf(ilid);
        } catch (Exception e) {

        }

        Branches branches = new Branches();
        branches.setBranId(AdminUserUtils.getPrincipal().getEmployee().getBranchesId());
        Branches bc = branchesService.findOneBranches(branches);


        IllCase illCase = new IllCase();
        illCase.setIllCaseId(illid);
        illCase = illCaseService.findOne(illCase);
        if (illCase == null) {
            return "redirect:/index";
        }
        if (illCase.getIllCaseState() != 4 && illCase.getIllCaseState() != 6) {
            return "redirect:/index";
        }
        EmployeeType empt = new EmployeeType();
        empt.setEmTypeId(AdminUserUtils.getPrincipal().getEtype());
        EmployeeType employeeType = employeeTypeService.findOneType(empt);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(illCase.getUserId());
        userInfo = userInfoService.findOne(userInfo);
        BabyInfo babyInfo = new BabyInfo();
        babyInfo.setBabyId(illCase.getBabyId());
        babyInfo = babyInfoService.findOne(babyInfo);
        VipInfo vipInfo = new VipInfo();
        vipInfo.setUserId(illCase.getUserId());
        vipInfo = vipInfoService.findOne(vipInfo);
        VipCard vipCard = new VipCard();
        vipCard.setVipId(vipInfo.getVipId());
        vipCard = vipCardService.findOne(vipCard);
        model.addAttribute("userinfo", userInfo);
        model.addAttribute("vipinfo", vipInfo);
        model.addAttribute("baby", babyInfo);
        model.addAttribute("illcase", illCase);
        model.addAttribute("vipcard", vipCard);
        model.addAttribute("branches", bc.getBranName());
        model.addAttribute("emId", AdminUserUtils.getPrincipal().getEmployee().getEmId());
        model.addAttribute("emName", employeeType.getTypeName());
        return "printHtml";
    }

    @RequestMapping("/updateIllCaseReserve")
    @ResponseBody
    public Object updateIllCaseReserve(IllCase illCase) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        int result = illCaseService.update(illCase);
        if (result > 0) {
            map.put("success", "更改成功");
        } else {
            map.put("error", "更改失败");
        }
        return map;
    }

    @RequestMapping("/recheck")
    @ResponseBody
    public Object reCheck(@RequestParam(value = "illid") String illid) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        Integer illids = null;
        try {
            illids = Integer.valueOf(illid);
        } catch (Exception e) {
            return result;
        }
        int res = illCaseService.reCheck(illids);
        if (res == 1) {
            result.put("success", true);
        }
        return result;
    }

    @RequestMapping("/getHistory")
    public Object getHistory(Model model, @Param("id") String id) {
        Integer illCaseId = null;
        try {
            illCaseId = Integer.valueOf(id);
            model.addAttribute("id", illCaseId);
        } catch (Exception e) {
            return "index";
        }
        IllCase tmp = new IllCase();
        tmp.setIllCaseId(illCaseId);
        IllCase illCase = illCaseService.findOne(tmp);
        if (illCase != null) {
            model.addAttribute("illCase", illCase);
        }
        return "prescriptionHistory";
    }

    @RequestMapping("/presettlPrice")
    @ResponseBody
    public Map preSettlementPrice(Prescription prescription) {
    Map result = new HashMap();
        //判断当前员工是否有结算权限
        Employee employee = AdminUserUtils.getPrincipal().getEmployee();
        EmployeeType employeeType = new EmployeeType();
        employeeType.setEmTypeId(employee.getEmTypeId());
        employeeType = employeeTypeService.findOneType(employeeType);
        if (employeeType != null) {
            //店长、管理员、收银员有结算权限
                Branches branches = new Branches();
                branches.setBranId(employee.getBranchesId());
                branches = branchesService.findOneBranches(branches);
                IllCase illCase = new IllCase();
                illCase.setIllCaseId(prescription.getIllCaseId());
                illCase = illCaseService.findOne(illCase);
                //判断该条病例信息是否存在
                if (illCase != null) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setId(illCase.getUserId());
                    //查询出当前用户对应的用户信息
                    userInfo = userInfoService.findOne(userInfo);
                    VipInfo vipInfo = new VipInfo();
                    vipInfo.setUserId(userInfo.getId());
                    //查询出当前对应的会员卡信息
                    vipInfo = vipInfoService.findOne(vipInfo);

                    //先判断会员卡类型，如果是体验卡，则扣除体验卡次数
                    VipCard vipCard = new VipCard();
                    vipCard.setVipId(vipInfo.getVipId());
                    vipCard = vipCardService.findOne(vipCard);
                    if (vipCard.getVipLevel() == 0) {
                        if (vipInfo.getRemainTime() == 0) {
                            result.put("msg", "该会员卡是体验卡，体验次数不足，请充值或者升级会员卡等级！");
                            result.put("isEnough",true);
                            return result;
                        }
                    }


                    //判断当前会员卡是否在当前店铺消费
                    if (vipInfo.getBranId() == employee.getBranchesId()) {
                        //查询出当前处方详情
                        if (prescription.getIllCaseId() == null || prescription.getPresDetail() == null ) {
                            result.put("msg", "信息不存在，不能计算价格！");
                            result.put("isEnough",true);
                            return result;
                        } else {
                            //结算处理
                            JSONArray jsonArray = JSONArray.fromObject("[" + prescription.getPresDetail() + "]");
                            List<Map> presDetailMap = new ArrayList<>();
                            for (int i = 0; i < jsonArray.size(); i++) {
                                Map<String, Object> map = (Map) jsonArray.get(i);
                                presDetailMap.add(map);
                            }

                            //将商品和穴位区分开map来；
                            //商品map
                            List<Map> dietaryMap = new ArrayList<>();
                            //穴位map
                            List<Map> nurseMap = new ArrayList<>();
                            for (int i = 0; i < presDetailMap.size(); i++) {
                                Map<String, Object> tmap = presDetailMap.get(i);
                                if ("nurse".equals(tmap.get("pretype").toString())) {
                                    //如果是穴位
                                    nurseMap.add(tmap);
                                } else if ("dietary".equals(tmap.get("pretype").toString())) {
                                    //如果是商品
                                    dietaryMap.add(tmap);
                                }
                            }
                            Product product = new Product();
                            product.setBranId(employee.getBranchesId());
                            //查询出当前分店的所有商品
                            List<Product> productList = productService.findProduct(product);


                            //比对商品是否满足，否则结算失败
                            //数量不够的商品noEnoughProduct里面
                            List<Map> noEnoughProduct = new ArrayList<>();
                            //该分店没有的商品
                            List<Map> noExistProduct = new ArrayList<>();
                            //处方所需要的所有商品记录
                            List<Product> needProducts = new ArrayList<>();
                            for (int i = 0; i < dietaryMap.size(); i++) {
                                Map<String, Object> pmap = dietaryMap.get(i);
                                boolean isExist = true;
                                for (int j = 0; j < productList.size(); j++) {
                                    Product tproduct = productList.get(j);
                                    if (pmap.get("prename").equals(tproduct.getReserve1())) {
                                        //存在的商品
                                        isExist = false;
                                        if (tproduct.getProStock() - 1 < Integer.valueOf(pmap.get("precount").toString())) {
                                            //库存不足
                                            noEnoughProduct.add(pmap);
                                        }
                                        tproduct.setState(Integer.valueOf(pmap.get("precount").toString()));
                                        needProducts.add(tproduct);
                                    }
                                }
                                if (isExist) {
                                    //不存在的商品
                                    noExistProduct.add(pmap);
                                }

                            }


                            Map tres = new HashMap();
                            if (noEnoughProduct.size() > 0) {
                                //商品数量不足
                                tres.put("msg", "商品库存不足");
                                tres.put("enough", noEnoughProduct);
                            }
                            if (noExistProduct.size() > 0) {
                                //商品数量不足
                                tres.put("msg1", "有商品不存在");
                                tres.put("noexist", noExistProduct);
                            }

                            //商品足够且满足全
                            if (noEnoughProduct.size() == 0 && noExistProduct.size() == 0) {
                                //判断是否有商品模板被更改
                                //所有的模板id
                                Set<Integer> tmpset = new HashSet<Integer>();
                                //1.取出所有的模板的商品,单个商品
                                //模板商品

                                Map<Integer, List> tmplateMap = new HashMap<>();
                                //单个商品，结算使用,status作为临时的购买量
                                List<Product> aloneProduct = new ArrayList<>();
                                for (int i = 0; i < dietaryMap.size(); i++) {
                                    Map map = dietaryMap.get(i);
                                    Integer tmpid = Integer.valueOf(map.get("pretemid").toString());
                                    if (tmpid == 0) {
                                        //单个商品
                                        for (int j = 0; j < needProducts.size(); j++) {
                                            if (needProducts.get(j).getReserve1().equals(map.get("prename"))) {
                                                Integer count = Integer.valueOf(map.get("precount").toString());
                                                needProducts.get(j).setState(count);
                                                if (!aloneProduct.contains(needProducts.get(j))){
                                                    aloneProduct.add(needProducts.get(j));
                                                }
                                            }
                                        }
                                    } else {
                                        // 所有模板商品
                                        tmpset.add(tmpid);
                                        if (tmplateMap.containsKey(tmpid)) {
                                            tmplateMap.get(tmpid).add(map);
                                        } else {
                                            List<Map> tmproduct = new ArrayList<>();
                                            tmproduct.add(map);
                                            tmplateMap.put(tmpid, tmproduct);
                                        }

                                    }
                                }
                                //遍历查出所有的模板集合
                                List<Template> nochangeTemp = new ArrayList<>();
                                //  List<Template> templateList = new ArrayList<>();
                                if (tmpset.size() > 0) {
                                    for (Integer tid : tmpset) {
                                        Template template = new Template();
                                        template.setTemId(tid);
                                        //数据库存储的模板数据
                                        template = templateService.findOne(template);
                                        //用户存储的模板数据
                                        List<Map> userProductList = tmplateMap.get(tid);
                                        if (template != null) {
                                            JSONArray tm = JSONArray.fromObject(template.getTemDetail());
                                            int count = 0;
                                            for (int i = 0; i < tm.size(); i++) {
                                                Map dbmap = (Map) tm.get(i);
                                                for (int j = 0; j < userProductList.size(); j++) {
                                                    Map usermap = userProductList.get(j);
                                                    Product tppp = new Product();
                                                    tppp.setProductId(Integer.valueOf(dbmap.get("Reid").toString()));
                                                    tppp = productService.findOne(tppp);
                                                    if (tppp.getReserve1().equals(usermap.get("prename")) && dbmap.get("productCount").equals("precount")) {
                                                        count++;
                                                    }
                                                }
                                            }
                                            if (count == tm.size()) {
                                                //没有改变模板
                                                nochangeTemp.add(template);
                                            } else {
                                                //模板已经改变
                                                for (int i = 0; i < tm.size(); i++) {
                                                    Map dbmap = (Map) tm.get(i);
                                                    Product tppp1 = new Product();
                                                    tppp1.setProductId(Integer.valueOf(dbmap.get("Reid").toString()));
                                                    tppp1 = productService.findOne(tppp1);
                                                    for (Product need : needProducts) {
                                                        if (need.getReserve1().equals(tppp1.getReserve1())) {
                                                            if (!aloneProduct.contains(need)){
                                                                aloneProduct.add(need);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                //  将nochangeTem和aloneProduct，nurseMap(穴位模板)传入即可做商品结算，剩下的是穴位结算
                                Map setlementMap = null;
                                try {
                                    setlementMap = productService.presettlementPrice(illCase, vipInfo, employee, branches, nochangeTemp, aloneProduct, nurseMap);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                boolean payres = (boolean) setlementMap.get("success");
                                String msg = "";
                                result = setlementMap;
                                result.put("isEnough",true);
//                                if (payres) {
////
////                                 //   msg = (String) setlementMap.get("msg");
////                                 //   result.put("success", true);
////                                } else {
////                                   msg = (String) setlementMap.get("msg");
////                                   result.put("msg", msg);
////                                }



                            } else {
                                result.put("data", tres);
                                result.put("isEnough",false);
                            }

                        }
                    } else {
                        result.put("msg", "会员卡和分店不符合");
                        result.put("isEnough",true);
                    }
                } else {
                    result.put("msg", "该信息不存在或该状态不能结算");
                    result.put("isEnough",true);
                }

        } else {
            result.put("msg", "该员工没有结算权限");
            result.put("enough",true);
        }
        return result;
    }

    @RequestMapping("/getVipCategory")
    @ResponseBody
    public Object getVipCategory(IllCase illCase){

        Map map = new HashMap();

        IllCase temp = illCaseService.findOne(illCase);
        VipInfo vipInfo = new VipInfo();
        vipInfo.setUserId(temp.getUserId());
        VipInfo vipInfoTemp = vipInfoService.findOne(vipInfo);
        VipCard vipCard = new VipCard();
        vipCard.setVipId(vipInfoTemp.getVipId());
        VipCard vipCardTemp = vipCardService.findOne(vipCard);
        if(vipCardTemp.getVipId()!=null&&vipInfoTemp.getVipId()!=null){
            map.put("success",true);
            map.put("data",vipCardTemp);
            map.put("money",vipInfoTemp);
        }else {
            map.put("success",false);
            map.put("msg","服务器异常");
        }
        return map;
    }
}

